package com.wonderful.eyepetizer.data.paging

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.wonderful.eyepetizer.data.entity.bean.BaseApiResult

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/2/21 17:04
 */
abstract class AbsPagingSource<T : Any>(private var refreshing: MutableState<Boolean>) :
    PagingSource<String, T>() {
    override fun getRefreshKey(state: PagingState<String, T>): String? = null

    override suspend fun load(params: LoadParams<String>): LoadResult<String, T> {
        return try {
            val pageKey: String? = params.key
            var nextKey: String? = null
            val nextPageUrl: String?
            val apiResult = if (pageKey.isNullOrEmpty()) {
                refreshing.value = true
                doLoadPage()
            } else {
                doLoadPage(pageKey)
            }
            nextPageUrl = apiResult.nextPageUrl
            if (!nextPageUrl.isNullOrEmpty()) {
                nextKey = nextPageUrl
            }
            refreshing.value = false
            LoadResult.Page(apiResult.itemList, null, nextKey)
        } catch (e: Exception) {
            Log.e("AbsPagingSource", "${e.message}")
            refreshing.value = false
            LoadResult.Error(e)
        }
    }

    abstract suspend fun doLoadPage(pageKey: String? = null): BaseApiResult<T>
}